package com.controller;

import com.example.pojo.User;
import com.example.service.UserService;
import com.userService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/org/user")
public class UserController1 {

    @Autowired
    private UserService userService;

    @GetMapping("/add")
    public String hello(@RequestBody User user) {
        userService.addUser(user);
        return "操作成功!";
    }

    /*
     * 新增用户
     * */
    @PostMapper("/userRegister")
    public JSONObject userAdd(HttpServletRequest request, HttpSession session) {
        //获取前端账号密码
        JSONObject jsonObject = new JSONObject();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //查询用户
        User user = userService.selectByUserName(username);
        if (user == null) {
            //注册成功
            userService.registerUser(user);
            jsonObject.put("code", 1);
            jsonObject.put("msg", "注册成功！");
            return jsonObject;
        }
        //注册失败，用户名已存在
        jsonObject.put("code", 0);
        jsonObject.put("msg", "用户名已存在！");
        return jsonObject;
    }

    /*
     * 用户登录
     * */
    @PostMapper("/userLogin")
    public JSONObject userLogin(HttpServletRequest request, HttpSession session) {
        //获取前端账号密码
        JSONObject jsonObject = new JSONObject();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //查询用户
        User user = userService.selectByUserName(username);
        if (user == null) {
            //查询不到用户
            jsonObject.put("code", 1);
            jsonObject.put("msg", "用户名错误！");
            return jsonObject;
        }
        //用户存在
        if (password.equals(user.getPassword)) {
            jsonObject.put("code",0);
            jsonObject.put("msg", "登录成功！");
            jsonObject.put("user",user);
            return jsonObject;
        }
        //密码不正确
        jsonObject.put("code",1);
        jsonObject.put("msg", "密码错误！");
        return jsonObject;
    }
}
